/*
**  ADClib.c
**	
*/
#include <p32xxxx.h>
#include "Bike_Display_ADC_Functions.h"
#include <peripheral/adc10.h>

// initialize the ADC for single conversion, select input pins
void AnalogStartupConfig( int nAnalogInputs) 
{
    TRISB |= ~nAnalogInputs; 
    AD1PCFG = nAnalogInputs; 
    
    //configure ADC Control Register 1
    AD1CON1bits.ADON = 0;       // Turn the ADC module off before setup
    AD1CON1bits.SSRC = 7;       // Auto start converting 
    AD1CON1bits.FORM = 0;       // Give result as unsigned int 
    AD1CON1bits.ASAM = 0; 
    
    //configure ADC Control Register 2
    AD1CON2 = 0;                // use MUXA, use AVdd & AVss as Vref+/-   
    
    //configure ADC Control Register 3
    AD1CON3bits.ADRC = 0;       // Conversion Clock Source 
    AD1CON3bits.SAMC = 0x1F;    // Auto-Sample Time bits  
    AD1CON3bits.ADCS = 0x3F;    // Conversion Clock Select bits 
    
    AD1CHS = 0;     
    //AD1CHSbits.CH0SA = nAnalogInputs; 
     
    AD1CSSL = 0;                // Scan None 
     
    AD1CON1bits.ON = 1;
        
} //initADC

int ReadAnalogInput(int nAnalogInput)
{
    AD1CHSbits.CH0SA = nAnalogInput;        // select analog input channel
    AD1CON1bits.SAMP = 1;                   // start sampling
    while (!AD1CON1bits.DONE);              // wait to complete conversion
    return ADC1BUF0;                        // read the conversion result
} // readADC
